package com.yueyi.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yueyi.common.constant.AuthServerConstant;
import com.yueyi.common.utils.HttpUtils;
import com.yueyi.common.utils.R;
import com.yueyi.gulimall.auth.feign.MemberFeignService;
import com.yueyi.gulimall.auth.vo.GiteeUser;
import com.yueyi.common.vo.MemberRespVo;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

import static com.yueyi.common.constant.AuthServerConstant.LOGIN_USER;

@Controller
public class OAuth2Controller {
    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>();
        Map<String, String> headers = new HashMap<>();
        Map<String, String> querys = new HashMap<>();
        map.put("grant_type", "authorization_code");
        map.put("client_id", "d570646e77ec7d31e0a31bc2fd06d5aace453a80f4843476f1d0e89758bf3490");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");
        map.put("client_secret", "04e03e4f9e17fc17e0f5a94d06c45754d3069976b8d87a66d7e012ff67746379");
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", headers, querys, map);
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到accessToken

            String json = EntityUtils.toString(response.getEntity());
            System.out.println("获取到的token为：" + json);
            JSONObject jsonObject = JSON.parseObject(json);
            String access_token = jsonObject.getString("access_token");
            Long expiresIn = jsonObject.getLong("expires_in");
            System.out.println("获取到的access_token：" + access_token);


            //gitee还需要再去请求user去获取数据
//            GiteeUser giteeUser =  giteeComponent.getGiteeUser(json);
            String urluser = "https://gitee.com/api/v5/user?access_token=" + access_token;
            HttpClient httpClientUser = HttpClientBuilder.create().build();
            HttpGet httpPostUser = new HttpGet(urluser);           //记得用httpGet请求，否则会405拒绝请求
            HttpResponse responseUser = httpClientUser.execute(httpPostUser);

            GiteeUser giteeUser = new GiteeUser();
            String user = EntityUtils.toString(responseUser.getEntity());
            System.out.println("gitee用户信息"+user);

            JSONObject jsonObjectUser = JSON.parseObject(user);
            String id = jsonObjectUser.getString("id");
            System.out.println(id);
            giteeUser.setId(id);
            giteeUser.setAccessToken(access_token);
            String name = jsonObjectUser.getString("name");
            System.out.println(name);
            giteeUser.setName(name);
            String bio = jsonObjectUser.getString("bio");
            System.out.println(bio);
            giteeUser.setBio(bio);
            giteeUser.setExpiresIn(expiresIn);

            //知道当前是哪个社交用户登录成功
            //1、当前用户如果是第一次进网站，就自动注册进来（为当前社交用户生成一个会员信息账号,以后这个社交账号就对应指定的会员）
            //登录或者注册这个社交用户
            R r = memberFeignService.oauthLogin(giteeUser);
            if (r.getCode() == 0) {
                MemberRespVo data = r.getData(new TypeReference<MemberRespVo>() {});
                System.out.println("登录成功，用户信息：" + data);
                session.setAttribute(LOGIN_USER, data);
                //2、登录成功就跳回首页
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            return "redirect:http://gulimall.com/login.html";
        }

    }

}
